﻿using System;
using System.IO;
using System.Xml;

namespace HOBA_SMSSender
{
    public static class FileUtility
    {
        /// <summary>
        /// Read the status response from Fibo of a just-sent SMS.
        /// </summary>
        /// <param name="xmlContent">Path of the XML response file;</param>
        /// <param name="code">Code number (200: success, 100: wrong username/password, 102: no credits left, 101: wrong recipient phone number, 103: wrong service type</param>
        /// <param name="message">Fibo's message;</param>
        /// <param name="time">The time this message arrives.</param>
        public static void ReadFiboSentStatus(String xmlContent, out String code, out String message, out String time)
        {
            XmlDocument sentStatusXml = new XmlDocument();
            sentStatusXml.LoadXml(xmlContent);

            code = sentStatusXml.GetElementsByTagName("Code")[0].InnerText;
            message = sentStatusXml.GetElementsByTagName("Message")[0].InnerText;
            time = sentStatusXml.GetElementsByTagName("Time")[0].InnerText;
        }

        /// <summary>
        /// Get the number of pages of customer's sms which each page contains at most 20 sms.
        /// </summary>
        /// <param name="filePath">Path of the XML response file.</param>
        /// <returns>The number of page.</returns>
        public static string ReadTotalPage(String xmlContent)
        {
            XmlDocument totalPage = new XmlDocument();
            totalPage.LoadXml(xmlContent);

            return totalPage.GetElementsByTagName("int")[0].InnerText;
        }

        /// <summary>
        /// Read the login status.
        /// </summary>
        /// <param name="filePath">Path of the XML response file.</param>
        /// <returns>True if login info is correct; otherwise, false.</returns>
        public static bool ReadCheckLogin(String xmlContent)
        {
            XmlDocument response = new XmlDocument();
            response.LoadXml(xmlContent);

            switch (response.GetElementsByTagName("Code")[0].InnerText)
            {
                case "0":
                    return true;
                case "100":
                    return false;
            }
            return false;
        }

        public static bool WriteLine(String filepath, String message, bool append)
        {
            StreamWriter targetFile = new StreamWriter(filepath, append, System.Text.Encoding.UTF8);
            targetFile.WriteLine(message);
            targetFile.Close();
            return true;
        }

        public static bool Write(String filepath, String message, bool append)
        {
            StreamWriter targetFile = new StreamWriter(filepath, append, System.Text.Encoding.UTF8);
            targetFile.Write(message);
            targetFile.Close();
            return true;
        }
    }
}
